// 测试数据库迁移 - 检查 reminder_minutes 字段是否正确添加
const { Pool } = require('pg');

async function testDatabaseMigration() {
  const pool = new Pool({
    user: process.env.DB_USER || 'postgres',
    host: process.env.DB_HOST || 'localhost',
    database: process.env.DB_NAME || 'aide_db',
    password: process.env.DB_PASSWORD || 'your_password',
    port: process.env.DB_PORT || 5432,
  });

  const client = await pool.connect();
  
  try {
    console.log('🔍 检查 tasks 表结构...');
    
    // 检查所有列
    const result = await client.query(`
      SELECT column_name, data_type, column_default, is_nullable
      FROM information_schema.columns 
      WHERE table_name = 'tasks' 
        AND table_schema = 'public'
      ORDER BY ordinal_position
    `);
    
    console.log('\n📋 tasks 表当前字段：');
    console.log('字段名'.padEnd(25), '数据类型'.padEnd(20), '默认值'.padEnd(15), '可空');
    console.log('-'.repeat(80));
    
    let hasReminderMinutes = false;
    
    for (const row of result.rows) {
      console.log(
        row.column_name.padEnd(25),
        row.data_type.padEnd(20),
        (row.column_default || 'NULL').padEnd(15),
        row.is_nullable
      );
      
      if (row.column_name === 'reminder_minutes') {
        hasReminderMinutes = true;
        console.log(`✅ 找到 reminder_minutes 字段: ${row.data_type}, 默认值: ${row.column_default}`);
      }
    }
    
    if (!hasReminderMinutes) {
      console.log('❌ reminder_minutes 字段缺失！');
    } else {
      console.log('\n✅ reminder_minutes 字段存在！');
    }
    
    // 测试插入一条带有 reminder_minutes 的任务
    console.log('\n🧪 测试插入任务...');
    
    const testTaskId = 'test-' + Date.now();
    await client.query(`
      INSERT INTO tasks (
        id, user_id, title, description, reminder_minutes, priority, category, notes, completed, status
      ) VALUES (
        $1, 'test-user', '测试任务', '测试描述', 15, 'P1', 'work', '测试备注', false, 'todo'
      )
    `, [testTaskId]);
    
    // 查询插入的任务
    const insertedTask = await client.query(`
      SELECT id, title, reminder_minutes, priority, created_at
      FROM tasks 
      WHERE id = $1
    `, [testTaskId]);
    
    if (insertedTask.rows.length > 0) {
      const task = insertedTask.rows[0];
      console.log(`✅ 任务插入成功:`);
      console.log(`   ID: ${task.id}`);
      console.log(`   标题: ${task.title}`);
      console.log(`   提醒间隔: ${task.reminder_minutes} 分钟`);
      console.log(`   优先级: ${task.priority}`);
      console.log(`   创建时间: ${task.created_at}`);
    } else {
      console.log('❌ 任务插入失败');
    }
    
    // 清理测试数据
    await client.query('DELETE FROM tasks WHERE id = $1', [testTaskId]);
    console.log('🗑️ 测试数据已清理');
    
  } catch (error) {
    console.error('❌ 数据库测试失败:', error.message);
    console.error('详细错误:', error);
  } finally {
    client.release();
    await pool.end();
  }
}

// 运行测试
testDatabaseMigration().then(() => {
  console.log('\n🎉 数据库迁移测试完成！');
  process.exit(0);
}).catch(error => {
  console.error('💥 测试过程中发生错误:', error);
  process.exit(1);
});
